﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VOL.Core.EFDbContext;
using VOL.Domain.Infrastructure;
using VOL.Domain.IServices.MasterData;
using VOL.Entity.DomainModels;

namespace VOL.Domain.Services.MasterData
{
    public class SupplierServices : ISupplierServices
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;

        public SupplierServices(IBaseRepository<Supplier> supplierRepository)
        {
            _supplierRepository = supplierRepository;
        }
        /// <summary>
        /// 添加供应商管理
        /// </summary>
        /// <param name="supplier"></param>
        /// <returns></returns>
        public async Task<int> AddSupplier(Supplier supplier)
        {
            try
            {
                var result = await _supplierRepository.Add(supplier);
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception($"添加供应商失败: {ex.Message}", ex);
            }
        }
        /// <summary>
        /// 供应商管理的显示
        /// </summary>
        /// <returns></returns>
        public async Task<List<Supplier>> GetAllSupplierList()
        {
            try
            {
                var supplierList = _supplierRepository.GetAll();
                return supplierList?.ToList() ?? new List<Supplier>();
            }
            catch (Exception ex)
            {
                throw new Exception($"获取供应商列表失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 根据Id获取单个供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<Supplier> GetSupplierById(int id)
        {
            return (await _supplierRepository.FindAsync(m => m.Id == id)).FirstOrDefault();
        }

        /// <summary>
        /// 更新供应商信息
        /// </summary>
        /// <param name="supplier"></param>
        /// <returns></returns>
        public async Task<int> UpdateSupplier(Supplier supplier)
        {
            return await _supplierRepository.Update(supplier);
        }

        /// <summary>
        /// 删除供应商
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DeleteSupplier(int id)
        {
            var supplier = (await _supplierRepository.FindAsync(s => s.Id == id)).FirstOrDefault();
            if (supplier == null) return 0;
            return await _supplierRepository.Delete(supplier);
        }
    }
}
